﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using InForTheCloud.OAuthLite;
using System.Net;
using System.IO;

namespace APIExplorer
{
    public class MainController
    {
        IMainView view;
        IMainViewModel model;
        public MainController(IMainView view, IMainViewModel model)
        {
            this.view = view;
            this.model = model;
        }

        public void Initialize()
        {
            var settings = APIExplorer.Properties.Settings.Default;

            model.AcceptMimeType = settings.ReturnType;
            model.CompanyAccountId = settings.CompanyAccountId;
            model.ConsumerKey = settings.ConsumerKey;
            model.ConsumerSecret = settings.ConsumerSecret;
            model.ContentType = settings.ContentType;
            model.Method = settings.Method;
            model.Request = settings.Request;
            model.RequestUrl = settings.RequestUrl;
            model.ThreeLegged = settings.ThreeLegged;
            model.Token = settings.Token;
            model.TokenSecret = settings.TokenSecret;

            view.ExecuteClicked += (sender, args) => {
                model.DebugLog = string.Empty;
                model.Response = string.Empty;
                try
                {

                    ExecuteRequest();

                }
                catch (Exception e) {
                    model.DebugLog = e.ToString();
                }
            };

            view.Closing += (sender, args) =>
            {
                settings.CompanyAccountId = model.CompanyAccountId;
                settings.ConsumerKey = model.ConsumerKey;
                settings.ConsumerSecret = model.ConsumerSecret;
                settings.ContentType = model.ContentType;
                settings.Method = model.Method;
                settings.Request = model.Request;
                settings.RequestUrl = model.RequestUrl;
                settings.ReturnType = model.AcceptMimeType;
                settings.ThreeLegged = model.ThreeLegged;
                settings.Token = model.Token;
                settings.TokenSecret = model.TokenSecret;
                settings.Save();
            };

            view.DataSource = model;
        }

        private void ExecuteRequest()
        {
            OAuthSecret oauthSecret = new OAuthSecret( model.ConsumerKey, model.ConsumerSecret);

            if ( model .ThreeLegged)
            {
                oauthSecret = new OAuthSecret ( model.ConsumerKey, model.ConsumerSecret, model.Token, model.TokenSecret);

            }
            var oauth = new OAuthClient(oauthSecret);
            oauth.Headers["Accept"] = model.AcceptMimeType;
            oauth.Headers["Accept-Encoding"] = "utf-8";
            oauth.Headers["Content-Type"] = model.ContentType;
            oauth.Headers["User-Agent"] = "DOTNET API Explorer/1.0";
            oauth.Headers["X-Tradeshift-TenantId"] = model.CompanyAccountId;
            try { 
                byte [] data = new byte [0];
                if (model.Method == "GET")
                {
                    data = oauth.DownloadData(model.RequestUrl);
                }
                else { 
                    var upload = Encoding .Default .GetBytes ( model.Request);

                    data = oauth.UploadData(model.RequestUrl, model.Method, upload);
                }

                var headers = oauth.ResponseHeaders.ToByteArray();
                model.DebugLog = new string(Encoding.Default.GetChars(headers));
                model.Response = new string(Encoding.Default.GetChars(data));
            }
            catch (WebException web)
            {
                using (var reader = new StreamReader(web.Response.GetResponseStream()))
                {
                    model.Response = reader.ReadToEnd();
                }
                var headers = web.Response.Headers.ToByteArray();
                model.DebugLog = new string(Encoding.Default.GetChars(headers));
            }


        }
    }
}
